<template>
  <div class="min-h-screen bg-gray-50 flex flex-col justify-center py-6 sm:py-12 px-4 sm:px-6 lg:px-8">
    <div class="sm:mx-auto sm:w-full sm:max-w-md">
      <!-- Logo -->
      <div class="flex justify-center">
        <RandomLogo />
      </div>
      <h2 class="mt-4 sm:mt-6 text-center text-2xl sm:text-3xl font-extrabold text-gray-900">
        创建新账户
      </h2>
      <p class="mt-2 text-center text-sm text-gray-600">
        加入馒头AI助手
      </p>
    </div>

    <div class="mt-6 sm:mt-8 sm:mx-auto sm:w-full sm:max-w-md">
      <div class="bg-white py-6 sm:py-8 px-4 shadow sm:rounded-lg sm:px-10">
        <!-- 注册表单 -->
        <form class="space-y-6" @submit.prevent="handleRegister">
          <div>
            <label for="username" class="block text-sm font-medium text-gray-700">
              用户名
            </label>
            <div class="mt-1 relative">
              <input
                id="username"
                name="username"
                type="text"
                required
                v-model="form.username"
                maxlength="12"
                minlength="4"
                pattern="[A-Za-z0-9]{4,12}"
                @blur="checkUserExist"
                @input="usernameExists = false; error = ''"
                class="appearance-none block w-full px-3 py-2 border border-gray-300 rounded-md placeholder-gray-400 focus:outline-none focus:ring-blue-500 focus:border-blue-500 sm:text-sm"
                placeholder="只能包含英文、数字和点号，至少3个字符"
              />
              <!-- 检查状态显示 -->
              <div v-if="usernameChecking" class="absolute right-3 top-2.5">
                <svg class="animate-spin h-5 w-5 text-gray-400" fill="none" viewBox="0 0 24 24">
                  <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
                  <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                </svg>
              </div>
              <div v-else-if="form.username && !userExist && !usernameError" class="absolute right-3 top-2.5">
                <svg class="h-5 w-5 text-green-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"></path>
                </svg>
              </div>
              <div v-else-if="userExist" class="absolute right-3 top-2.5">
                <svg class="h-5 w-5 text-red-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>
                </svg>
              </div>
            </div>
          </div>

          <div>
            <label for="password" class="block text-sm font-medium text-gray-700">
              密码
            </label>
            <div class="mt-1">
              <input
                id="password"
                name="password"
                type="password"
                required
                v-model="form.password"
                class="appearance-none block w-full px-3 py-2 border border-gray-300 rounded-md placeholder-gray-400 focus:outline-none focus:ring-blue-500 focus:border-blue-500 sm:text-sm"
                placeholder="请输入密码"
              />
            </div>
          </div>

          <div>
            <label for="confirmPassword" class="block text-sm font-medium text-gray-700">
              确认密码
            </label>
            <div class="mt-1">
              <input
                id="confirmPassword"
                name="confirmPassword"
                type="password"
                required
                v-model="form.confirmPassword"
                class="appearance-none block w-full px-3 py-2 border border-gray-300 rounded-md placeholder-gray-400 focus:outline-none focus:ring-blue-500 focus:border-blue-500 sm:text-sm"
                placeholder="请再次输入密码"
              />
            </div>
          </div>

          <div>
            <button
              type="submit"
              :disabled="loading || userExist.value"
              class="w-full flex justify-center py-2 px-4 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-blue-600 hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 disabled:opacity-50"
            >
              <span v-if="loading">注册中...</span>
              <span v-else>注册</span>
            </button>
          </div>

          <div class="text-center">
            <router-link
              to="/login"
              class="text-sm text-blue-600 hover:text-blue-500"
            >
              已有账户？立即登录
            </router-link>
          </div>
        </form>

        <!-- 错误提示 -->
        <div v-if="error" class="mt-4 p-3 bg-red-50 border border-red-200 rounded-md">
          <p class="text-sm text-red-600">{{ error }}</p>
        </div>

        <!-- 成功提示 -->
        <div v-if="success" class="mt-4 p-3 bg-green-50 border border-green-200 rounded-md">
          <p class="text-sm text-green-600">{{ success }}</p>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { useRouter } from 'vue-router'
import { register, getUserList, getUserName } from '../api/index'
import RandomLogo from '../components/RandomLogo.vue'

const router = useRouter()

const form = ref({
  username: '',
  password: '',
  confirmPassword: ''
})

const loading = ref(false)
const error = ref('')
const success = ref('')
const usernameChecking = ref(false)
const usernameExists = ref(false)
const usernameError = ref('')
const userExist = ref(false)

// 新增：根据日期生成随机logo索引
const today = new Date().toISOString().slice(0, 10)
const logoIndex = computed(() => {
  const hash = today.split('-').join('')
  return parseInt(hash, 10) % 5 // 假设有5个logo
})

// 检查用户名是否存在
const checkUserExist = async () => {
  if (!/^[A-Za-z0-9]{4,12}$/.test(form.value.username)) {
    usernameError.value = '用户名只能为4-12位数字或字母';
    userExist.value = false;
    return;
  }
  const res = await getUserName(form.value.username);
  if (res && res.data == null) {
    usernameError.value = '';
    userExist.value = false;
  } else {
    usernameError.value = '用户名已存在';
    userExist.value = true;
  }
}

// 注册处理
const handleRegister = async () => {
  if (userExist.value) {
    error.value = '用户名已存在';
    return;
  }

  if (!form.value.username || !form.value.password || !form.value.confirmPassword) {
    error.value = '请填写完整信息'
    return
  }

  // 用户名格式验证
  const usernameRegex = /^[A-Za-z0-9.]{3,}$/
  if (!usernameRegex.test(form.value.username)) {
    error.value = '用户名只能包含英文字母、数字和点号，且不少于3个字符'
    return
  }

  if (form.value.password !== form.value.confirmPassword) {
    error.value = '两次输入的密码不一致'
    return
  }

  if (form.value.password.length < 6) {
    error.value = '密码长度至少6位'
    return
  }

  loading.value = true
  error.value = ''
  success.value = ''

  try {
    const response = await register({
      username: form.value.username,
      password: form.value.password
    })

    console.log('注册API响应:', response)

    if (response.code == 200) {
      success.value = '注册成功，3秒后跳转到登录页面'
      setTimeout(() => {
        router.push('/login')
      }, 3000)
    } else {
      error.value = response.message || '注册失败'
    }
  } catch (err) {
    console.error('注册请求失败:', err)
    error.value = err.response?.data?.message || '注册失败，请稍后重试'
  } finally {
    loading.value = false
  }
}
</script> 